package com.youan.log.configuration;

import com.baomidou.dynamic.datasource.processor.DsHeaderProcessor;
import com.baomidou.dynamic.datasource.processor.DsProcessor;
import com.baomidou.dynamic.datasource.processor.DsSessionProcessor;
import com.baomidou.dynamic.datasource.processor.DsSpelExpressionProcessor;
import org.aopalliance.intercept.MethodInvocation;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
@MapperScan(basePackages = {"com.youan.log.**.mapper"})
public class YAMyBatisPlusConfiguration {


    /**
     * #动态数据源功能关闭后如果存在 @TenantDS 注解会因为无法解析spel表达式报错,框架的消息通知自带该注解
     * 关闭数据源功能: tenant.dynamic-datasource: false
     * @author xsh
     * @date 2021/1/11 8:38
     * @param:
     * @return
     */
    @Bean
    public DsProcessor dsProcessor() {
        DsHeaderProcessor headerProcessor = new DsHeaderProcessor();
        DsSessionProcessor sessionProcessor = new DsSessionProcessor();
        DsYATenantIdProcessor tenantIdProcessor = new DsYATenantIdProcessor();
        DsSpelExpressionProcessor spelExpressionProcessor = new DsSpelExpressionProcessor();
        headerProcessor.setNextProcessor(sessionProcessor);
        sessionProcessor.setNextProcessor(tenantIdProcessor);
        tenantIdProcessor.setNextProcessor(spelExpressionProcessor);
        return headerProcessor;
    }
}


class DsYATenantIdProcessor extends DsProcessor {

    public static final String TENANT_ID_KEY = "#token.tenantId";

    @Override
    public boolean matches(String key)	 {
        return key.equals(TENANT_ID_KEY);
    }

    @Override
    public String doDetermineDatasource(MethodInvocation invocation, String key) {
        return "master";
    }

}
